package com.leyou.user.web;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.interceptors.LoginInterceptor;
import com.leyou.auth.utils.UserContext;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/info")
public class UserController {


    @Autowired
    private UserService userService;


    //todo 根据 账号 密码 查询 用户信息 登录需要!!
    @GetMapping
    public ResponseEntity<UserDTO> queryByUnameAndPwd(
            @RequestParam("username") String username,
            @RequestParam("password") String password) {
        return ResponseEntity.ok(userService.queryByUnameAndPwd(username,password));

    }

    /**
     * todo 注册账号 添加账号
     * todo @Valid 开启拦截业务
     * @param user
     * @param code
     * @return
     */
    @PostMapping
    public ResponseEntity<Void>logonUser(
             @Valid User user,
            @RequestParam("code")String code
    ){

        userService.logonUser(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();

    }


    /**
     * todo 发送短信验证码
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void>sendCode(@RequestParam("phone")String phone){

        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.CREATED).build();

    }

    /**
     * todo 判断信息是否存在
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean>isExist(@PathVariable("data")String data,@PathVariable("type")Integer type){

        return ResponseEntity.ok(userService.isExist(data, type));
    }


    /**
     *todo 获取一个cookie 名称叫 test
     * @param token
     * @return
     */
    @GetMapping("/me")//todo 新加功能 获取用户信息
    public ResponseEntity<UserDetail>checkLogin(//HttpServletRequest request
    @CookieValue("LY_TOKEN") String token
    ){

       /* Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
             if ("test".equals(cookie.getName())) {
                cookie.getValue();
            } //这么多等同于@CookieValue("test") String token
        }*/

       //究极版
        return ResponseEntity.ok(UserContext.getUser());
      // return ResponseEntity.ok(LoginInterceptor.getUserDetail());
      //  return ResponseEntity.ok(this.userService.checkLogin(token));

    }



}
